package easyzhou.com.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class IOUtil {
	public static final String toString(InputStream inputStream, String charset) {
		return doToString(inputStream, charset);

	}

	private static String doToString(InputStream inputStream, String charset) {
		Reader reader = null;
		StringBuilder resule = new StringBuilder();
		try {
			// 一次读多个字符
			char[] tempchars = new char[30];
			int charread = 0;
			reader = new InputStreamReader(inputStream);
			// 读入多个字符到字符数组中，charread为一次读取字符数
			while ((charread = reader.read(tempchars)) != -1) {
				// 同样屏蔽掉\r不显示
				if ((charread == tempchars.length)
						&& (tempchars[tempchars.length - 1] != '\r')) {
					resule.append(tempchars);
				} else {
					for (int i = 0; i < charread; i++) {
						if (tempchars[i] == '\r') {
							continue;
						} else {
							resule.append(tempchars[i]);
						}
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return resule.toString();
	}

	public static void copy(String sourcePath, String targetPath)
			throws IOException {
		File source = new File(sourcePath);
		File target = new File(targetPath);
		copy(source, target);

	}

	public static void copy(File source, File target) throws IOException {

		FileInputStream inputStream = new FileInputStream(source);
		FileOutputStream outputStream = new FileOutputStream(target);
		// 一次读多个字符
		byte[] bs = new byte[30];
		int charread = 0;
		// 读入多个字符到字符数组中，charread为一次读取字符数
		while ((charread = inputStream.read(bs)) != -1) {
			// 同样屏蔽掉\r不显示
			outputStream.write(bs, 0, charread);
		}
		inputStream.close();
		outputStream.close();

	}

	public static String toString(File file, String charset) {
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return doToString(inputStream, charset);
	}

	public static void main(String[] args) {
		String str = toString(
				new File(
						"/Users/mjorcen/works/Workspaces/eclipse_workspaces/workspace00/jzmao_user/pom.xml"),
				"utf-8");
		System.out.println(str);
	}

}
